package offer; /**
 * Creared with IntelliJ IDEA.
 * Description:
 * User:yxd
 * Date:2022-07-01
 * Time:22:56
 */

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
public class JZ23 {

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        ListNode fast = pHead;
        ListNode slow = pHead;
        //快慢指针
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            //设置快慢指针，假如有环，他们最后一定相遇。
            //如果相等,就退出
            if(fast == slow){
                break;
            }
        }

        if(fast == null || fast.next == null){
            return null;
        }
        slow = pHead;
        //两个指针分别从链表头和相遇点继续出发，每次走一步，最后一定相遇与环入口。
        while(fast != slow){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;



    }
}

